package com.aizhixin.lab.quartz.controller;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.account.service.AccountService;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.utils.TokenUtil;
import com.aizhixin.lab.company.controller.WebSocketServer;
import com.aizhixin.lab.company.domain.SignData;
import com.aizhixin.lab.course.course.service.ReleaseSignInService;
import com.aizhixin.lab.quartz.domain.ReleaseProjectSignDomain;
import com.aizhixin.lab.quartz.domain.ReleaseSignDomain;
import com.aizhixin.lab.quartz.entity.QuartzJob;
import com.aizhixin.lab.quartz.entity.SignInfo;
import com.aizhixin.lab.quartz.repository.QuartzJobRepository;
import com.aizhixin.lab.quartz.repository.SignInfoRepository;
import com.aizhixin.lab.quartz.service.QuartzJobService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 定时任务在线管理
 */
@RestController
@RequestMapping("/api/v1/sys/quartzJob")
@Slf4j
@Api(tags = "定时任务接口")
public class QuartzJobController {
    @Autowired
    private QuartzJobService quartzJobService;
    @Autowired
    private QuartzJobRepository quartzJobRepository;
    @Autowired
    private AccountService accountService;
    @Autowired
    private SignInfoRepository repository;
    @Autowired
    private ReleaseSignInService signInService;
    @RequestMapping(value = "/releaseSign", method = RequestMethod.POST)
    public ResponseEntity<?> releaseSign(@RequestHeader("Authorization") String token,
                                         @RequestBody ReleaseSignDomain domain) {
        Map<String, Object> result = new HashMap<>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        if (domain.getSignDate() != null) {
            if (new Date().getTime() > domain.getSignDate().getTime()) {
                result.put(ApiReturnConstants.SUCCESS, false);
                result.put(ApiReturnConstants.MESSAGE, "开始签到时间不能小于当前时间");
                return new ResponseEntity(result, HttpStatus.OK);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date(domain.getSignDate().getTime() + 5000L));                    //放入Date类型数据
            Integer year = calendar.get(Calendar.YEAR);//获取年份
            Integer month = calendar.get(Calendar.MONTH);//获取月份
            Integer date = calendar.get(Calendar.DATE);                    //获取日
            Integer hour = calendar.get(Calendar.HOUR_OF_DAY);                //时（24小时制）
            Integer minute = calendar.get(Calendar.MINUTE);                    //分
            Integer second = calendar.get(Calendar.SECOND);                    //秒
            String corn = second + " " + (minute) + " " + hour + " " + date + " " + (month + 1) + " ? " + year;
//        String corn="0/1 * * * * ?";
            SignInfo signInfo = new SignInfo();
            signInfo.setCourseClassId(domain.getCourseClassId());
            signInfo.setEndDate(domain.getEndDate());
            signInfo.setSignDate(domain.getSignDate());
            signInfo.setCreateBy(account.getId());
            signInfo.setType(10);
            SignInfo save = repository.save(signInfo);
            QuartzJob quartzJob = new QuartzJob();
            quartzJob.setStatus(0);
            quartzJob.setCreateBy(account.getId() + "");
            quartzJob.setCronExpression(corn);
            quartzJob.setJobClassName("com.aizhixin.lab.quartz.job.ReleaseSignJob");
            quartzJob.setParameter(save.getId() + "");
            quartzJob.setReleaseDate(domain.getSignDate());
            quartzJob.setCreateTime(new Date());
            quartzJobService.saveAndScheduleJob(quartzJob);
            result.put(ApiReturnConstants.SUCCESS, true);

        } else {
            SignData signData = signInService.releaseSign(domain.getCourseClassId(), new Date(domain.getSignDate().getTime() + 1000L * 60 * 5), account.getId(), 10);
            List<String> ids = signData.getIds();
            for (String id:ids){
                WebSocketServer webSocketServer = WebSocketServer.getWebSocketSet().get(id);
                if (webSocketServer != null) {
//                    webSocketServer.sendMessage("你是谁");
                    webSocketServer.getSession().getAsyncRemote().sendText("老师提醒你签到了,"+signData.getSignInCode());
                }
            }
            result.put(ApiReturnConstants.SUCCESS, true);
        }
        return new ResponseEntity(result, HttpStatus.OK);

    }

    @RequestMapping(value = "/releaseProjectSign", method = RequestMethod.POST)
    public ResponseEntity<?> releaseProjectSign(@RequestHeader("Authorization") String token,
                                                @RequestBody ReleaseProjectSignDomain domain) {
        Map<String, Object> result = new HashMap<>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        if (new Date().getTime() > domain.getSignDate().getTime()) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.MESSAGE, "开始签到时间不能小于当前时间");
            return new ResponseEntity(result, HttpStatus.OK);
        }


        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(domain.getSignDate().getTime() + 5000L));                    //放入Date类型数据
        Integer year = calendar.get(Calendar.YEAR);//获取年份
        Integer month = calendar.get(Calendar.MONTH);//获取月份
        Integer date = calendar.get(Calendar.DATE);                    //获取日
        Integer hour = calendar.get(Calendar.HOUR_OF_DAY);                //时（24小时制）
        Integer minute = calendar.get(Calendar.MINUTE);                    //分
        Integer second = calendar.get(Calendar.SECOND);                    //秒
        String corn = second + " " + (minute) + " " + hour + " " + date + " " + (month + 1) + " ? " + year;
//        String corn="0/1 * * * * ?";
        SignInfo signInfo = new SignInfo();
        signInfo.setCourseClassId(domain.getProjectClassId());
        signInfo.setEndDate(domain.getEndDate());
        signInfo.setSignDate(domain.getSignDate());
        signInfo.setCreateBy(account.getId());
        signInfo.setType(20);
        SignInfo save = repository.save(signInfo);
        QuartzJob quartzJob = new QuartzJob();
        quartzJob.setStatus(0);
        quartzJob.setCreateBy(account.getId() + "");
        quartzJob.setCronExpression(corn);
        quartzJob.setJobClassName("com.aizhixin.lab.quartz.job.ReleaseSignJob");
        quartzJob.setParameter(save.getId() + "");
        quartzJob.setReleaseDate(domain.getSignDate());
        quartzJob.setCreateTime(new Date());
        quartzJobService.saveAndScheduleJob(quartzJob);
        result.put(ApiReturnConstants.SUCCESS, true);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    /**
     * 添加定时任务
     *
     * @param quartzJob
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseEntity<?> add(@RequestBody QuartzJob quartzJob) {
        List<QuartzJob> list = quartzJobService.findByJobClassName(quartzJob.getJobClassName());
//		if (list != null && list.size() > 0) {
//			return new ResponseEntity<Object>("该定时任务类名已存在",
//					HttpStatus.UNAUTHORIZED);
//		}
        QuartzJob job = quartzJobService.saveAndScheduleJob(quartzJob);
        return new ResponseEntity(job, HttpStatus.OK);
    }

    /**
     * 更新定时任务
     *
     * @param quartzJob
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public ResponseEntity<?> eidt(@RequestBody QuartzJob quartzJob) {
        try {
            quartzJobService.editAndScheduleJob(quartzJob);
        } catch (SchedulerException e) {
            log.error(e.getMessage(), e);
            return new ResponseEntity("更新定时任务失败!", HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity("更新定时任务成功!", HttpStatus.OK);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    //@RequiresRoles("admin")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public ResponseEntity<?> delete(@RequestParam(name = "id", required = true) String id) {
        QuartzJob quartzJob = quartzJobRepository.findOne(id);
        if (quartzJob == null) {
            return new ResponseEntity("未找到对应实体", HttpStatus.UNAUTHORIZED);
        }
        quartzJobService.deleteAndStopJob(quartzJob);
        return new ResponseEntity("删除成功!", HttpStatus.OK);

    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    //@RequiresRoles("admin")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public ResponseEntity<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return new ResponseEntity("参数不识别", HttpStatus.UNAUTHORIZED);
        }
        for (String id : Arrays.asList(ids.split(","))) {
            QuartzJob job = quartzJobRepository.findOne(id);
            quartzJobService.deleteAndStopJob(job);
        }
        return new ResponseEntity("删除定时任务成功!", HttpStatus.OK);
    }

    /**
     * 暂停定时任务
     *
     * @param jobClassName
     * @return
     */
    //@RequiresRoles("admin")
    @GetMapping(value = "/pause")
    @ApiOperation(value = "暂停定时任务")
    public ResponseEntity<Object> pauseJob(@RequestParam(name = "jobClassName", required = true) String jobClassName) {
        List<QuartzJob> job = quartzJobService.findByJobClassName(jobClassName);
        if (job.size() <= 0) {
            return new ResponseEntity("定时任务不存在", HttpStatus.UNAUTHORIZED);
        }
        quartzJobService.pause(job.get(0));
        return new ResponseEntity("暂停定时任务成功!", HttpStatus.OK);
    }

    /**
     * 启动定时任务
     *
     * @param jobClassName
     * @return
     */
    //@RequiresRoles("admin")
    @GetMapping(value = "/resume")
    @ApiOperation(value = "恢复定时任务")
    public ResponseEntity<Object> resumeJob(@RequestParam(name = "jobClassName", required = true) String jobClassName) {
//		List<QuartzJob> job = quartzJobService.findByJobClassName(jobClassName);
        QuartzJob one = quartzJobService.findOne(jobClassName);
        if (Objects.isNull(one)) {
            return new ResponseEntity("定时任务不存在", HttpStatus.UNAUTHORIZED);
        }
        quartzJobService.resumeJob(one);
        return new ResponseEntity("恢复定时任务成功!", HttpStatus.OK);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public ResponseEntity<?> queryById(@RequestParam(name = "id", required = true) String id) {
        QuartzJob quartzJob = quartzJobRepository.findOne(id);
        return new ResponseEntity(quartzJob, HttpStatus.OK);
    }


    /**
     * 立即执行
     *
     * @param id
     * @return
     */
    //@RequiresRoles("admin")
    @GetMapping("/execute")
    public ResponseEntity<?> execute(@RequestParam(name = "id", required = true) String id) {
        QuartzJob quartzJob = quartzJobRepository.findOne(id);
        if (quartzJob == null) {
            return new ResponseEntity("未找到对应实体", HttpStatus.UNAUTHORIZED);
        }
        try {
            quartzJobService.execute(quartzJob);
        } catch (Exception e) {
            //e.printStackTrace();
            log.info("定时任务 立即执行失败>>" + e.getMessage());
            return new ResponseEntity("执行失败!", HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity("执行成功!", HttpStatus.OK);
    }
}
